//
//  CEAccoutSettingVC.m
//  digitalCurrency
//
//  Created by 默认账户 on 2019/4/3.
//  Copyright © 2019 XinHuoKeJi. All rights reserved.
//

#import "CEAccoutSettingVC.h"
#import "CESecretVC.h"
#import "LoginNetManager.h"
#import "YLTabBarController.h"
#import "MineNetManager.h"
#import "VersionUpdateModel.h"
#import "WMHTMLViewController.h"
#import "CTLanguageVC.h"
#import "AddressManageVC.h"
@interface CEAccoutSettingVC ()

@property (nonatomic, copy) NSArray *titles;
@property (nonatomic, strong) UIButton *exitbtn;
@property (nonatomic, strong) VersionUpdateModel *versionModel;
@property (nonatomic, copy) NSString *version;

@end

@implementation CEAccoutSettingVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    self.version = [NSString stringWithFormat:@"V %@", app_Version];
    
    [self.view addSubview:self.tableView];
    self.tableView.rowHeight = 50;
    self.tableView.frame     = CGRectMake(0, 0, SCREEN_WIDTH, 270);
    self.tableView.separatorColor = [UIColor clearColor];
    
    [self.view addSubview:self.exitbtn];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.viewTitle.text = LocalizationKey(@"Account setting");
    _titles = @[LocalizationKey(@"Password setting"),LocalizationKey(@"地址管理"),LocalizationKey(@"language"),LocalizationKey(@"Check update")];

    [_exitbtn setTitle:LocalizationKey(@"Logout") forState:UIControlStateNormal];

    [self.tableView reloadData];
}

- (void)exitapp {
    [EasyShowLodingView showLodingText:[[ChangeLanguage bundle] localizedStringForKey:@"logOutTip" value:nil table:@"English"]];
    
    [LoginNetManager LogoutForCompleteHandle:^(id resPonseObj, int code) {
        [EasyShowLodingView hidenLoding];
        if (code) {
            [YLUserInfo logout];
            
            [self showLoginViewController];

//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                YLTabBarController *SectionTabbar = [[YLTabBarController alloc] init];
//                APPLICATION.window.rootViewController=SectionTabbar;
//            });
            
//            if ([resPonseObj[@"code"] integerValue] == 0) {
//
//                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                    YLTabBarController *SectionTabbar = [[YLTabBarController alloc] init];
//                    APPLICATION.window.rootViewController=SectionTabbar;
//                });
//            }
//            else {
//                [self.view makeToast:resPonseObj[MESSAGE] duration:1.5 position:CSToastPositionCenter];
//            }
        }
        else {
            [self.view makeToast:LocalizationKey(@"noNetworkStatus") duration:1.5 position:CSToastPositionCenter];
        }
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _titles.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"setcell"];
    if (nil == cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"setcell"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    UIView *lineView = [[UIView alloc]init];
    [cell.contentView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(17);
        make.right.equalTo(-17);
        make.bottom.equalTo(0);
        make.height.equalTo(0.5);
    }];
    lineView.backgroundColor = tTableViewCellLine;
    
    if (indexPath.row != _titles.count-1) {
        cell.accessoryType  = UITableViewCellAccessoryDisclosureIndicator;
    }
    else {
        UILabel *versionLabel = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-185, 15, 160, 20)];
        versionLabel.text      = self.version;
        versionLabel.textColor = [UIColor colorWithHEX:@"c0c2c6"];
        versionLabel.textAlignment = NSTextAlignmentRight;
        [cell.contentView addSubview: versionLabel];
        
    }
    cell.textLabel.text = _titles[indexPath.row];
    cell.textLabel.textColor = tThreeColor;
    
    if (indexPath.row == _titles.count-2) {
        NSString *lang = [[NSUserDefaults standardUserDefaults] objectForKey:@"language"];
        if (!lang) {
            NSString *currLanguage = [[NSUserDefaults standardUserDefaults] valueForKey:LocalLanguageKey];
            if ([currLanguage isEqualToString:@"en"]) {
                lang = @"english";
            }
            else {
                lang = @"chinese";
            }
        }
        cell.detailTextLabel.text = LocalizationKey(lang);
        cell.detailTextLabel.textColor = tThreeColor;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.row == 0) {
        CESecretVC *sec = [[CESecretVC alloc] init];
        [self.navigationController pushViewController:sec animated:YES];
    }
    else if (indexPath.row == 1) {
        AddressManageVC *vc = [[AddressManageVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
//    else if (indexPath.row == 2) {
//        WMHTMLViewController *aboutC = [[WMHTMLViewController alloc] init];
//        if ([[[NSUserDefaults standardUserDefaults] objectForKey:LocalLanguageKey] isEqualToString:@"en"]) {
//            aboutC.htmlUrl = @"https://compasschain.io/download/CommonProblems-cn.html?lang=en";
//        }
//        else {
//            aboutC.htmlUrl = @"https://compasschain.io/download/CommonProblems-cn.html?lang=cn";
//        }
//        aboutC.webViewTitle = LocalizationKey(@"Use help");
//        CGFloat bottomH     = kEasyShowSafeBottomMargin_S;
//        aboutC.webViewRect  = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - kTopHeight - bottomH);
//        aboutC.canScroll    = YES;
//        aboutC.showProgressView = YES;
//        [self.navigationController pushViewController:aboutC animated:YES];
//    }
    else if (indexPath.row == _titles.count-1) {
        [self versionUpdate];
    }
    else {
        CTLanguageVC *language = [[CTLanguageVC alloc] init];
        [self.navigationController pushViewController:language animated:YES];
    }
}

#pragma mark - 版本更新接口请求
-(void)versionUpdate {
    [MineNetManager versionUpdateForId:@"1" CompleteHandle:^(id resPonseObj, int code) {
        NSLog(@"版本更新接口请求 --- %@",resPonseObj);
        if (code) {
            if ([resPonseObj[@"code"] integerValue] == 0) {
                self.versionModel = [VersionUpdateModel mj_objectWithKeyValues:resPonseObj[@"data"]];
                // app当前版本
                NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
                NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
                
                if ([app_Version compare:_versionModel.version_code] == NSOrderedSame ||[app_Version compare:_versionModel.version_code] == NSOrderedDescending) {
                    //不需要更新
                    [self.view makeToast:@"已是最新版本" duration:1.5 position:CSToastPositionCenter];
                }
                else {
                    //版本更新
                    NSURL *url = [NSURL URLWithString:_versionModel.url];
                    
                    [LEEAlert alert].config
                    .LeeTitle(LocalizationKey(@"warmPrompt"))
                    .LeeAddContent(^(UILabel *label) {
                        label.text = LocalizationKey(@"当前有新的版本，请前往下载升级！");
                        label.font = [UIFont systemFontOfSize:16];
                    })
                    .LeeAddAction(^(LEEAction *action) {
                        action.title      = LocalizationKey(@"ok");
                        action.titleColor = kRGBColor(43, 43, 43);
                        action.font       = [UIFont systemFontOfSize:16];
                        action.clickBlock = ^{
                            if ([[UIApplication sharedApplication] respondsToSelector:@selector(openURL:options:completionHandler:)]) {
                                [[UIApplication sharedApplication]
                                 openURL:url
                                 options:@{}
                                completionHandler:nil];
                            }
                        };
                    })
                    .LeeShow();
                }
            }
            else if ([resPonseObj[@"code"] integerValue]==4000||[resPonseObj[@"code"] integerValue]==3000) {
            }
            else if ([resPonseObj[@"code"] integerValue] == 500) {
                //无版本更新，不提示
            }
        }
    }];
}

- (UIButton *)exitbtn {
    if (!_exitbtn) {
        _exitbtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _exitbtn.layer.cornerRadius = 22.0;
        [_exitbtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _exitbtn.backgroundColor = [UIColor colorWithHEX:maincolor];
        _exitbtn.titleLabel.font = [UIFont systemFontOfSize:17];
        _exitbtn.frame = CGRectMake(23, 310, SCREEN_WIDTH-46, 44);
        _exitbtn.hidden = YES;
        [_exitbtn addTarget:self action:@selector(exitapp) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _exitbtn;
}

@end
